/*初始化函数*/
function init() {
    // 初始化查询值
    $("input[name='search_phone']").val("");
    $("input[name='search_username']").val("");
    $("input[name='search_blog_number_min']").val("");
    $("input[name='search_blog_number_max']").val("");
    // 1.加载角色信息列表
    $.get("/role/info", {"token": localStorage.getItem("token")}, function (result) {
        if (result.code === 200) {
            let html_str = "";
            $.each(result.data, function (i, n) {
                html_str += '<input type="radio" name="role_id" value="' + n.id + '" title="' + n.name + '">';
            })
            $("#role_div").html(html_str);
            // 默认选中personal
            $("input[type='radio'][name='role_id'][title='personal']").attr("checked", true);
            layui.form.render('radio'); //刷新radio框渲染
        } else if (result.code === 401)
            window.parent.location.href = "/login.html";
        else
            layer.msg(result.msg, {icon: 5});
    })

    // 查询
    pageList(1,5,true);
}

layui.use(['layer', 'form', 'laypage'], function () {
    let layer = layui.layer, form = layui.form, laypage = layui.laypage;

    // 1.查询按钮
    $("#search_btn").click(function () {
        $("input[name='hidden_phone']").val($.trim($("input[name='search_phone']").val()));
        $("input[name='hidden_username']").val($.trim($("input[name='search_username']").val()));
        $("input[name='hidden_blog_number_min']").val($.trim($("input[name='search_blog_number_min']").val()));
        $("input[name='hidden_blog_number_max']").val($.trim($("input[name='search_blog_number_max']").val()));

        // 执行分页查询函数
        pageList(1, 5, true);
    })

    // 2.全选按钮
    let $check_all = $("input[type='checkbox'][name='check_all']")
    $check_all.click(function () {
        $("input[type='checkbox'][name='user_id']").prop("checked", $check_all.prop("checked"));
    })
    $("#user_list").on("click", "input[name='user_id']", function () {
        let flag = $("input[type='checkbox'][name='user_id']").length === $("input[type='checkbox'][name='user_id']:checked").length;
        $check_all.prop("checked", flag);
    })

    // 3.增加按钮
    $("#add_btn").click(function () {
        let add_layer_index = layer.open({
            type: 1,
            title: "增加",
            content: $("#add_edit_layer"),
            closeBtn: 2,
            //anim: 3,
            success: function (layero, index) {
                $("#reset_btn").removeClass("layui-btn-disabled").prop("disabled", false).click();//清空值
                $("input[name='phone']").prop("disabled", false);
                $("input[name='username']").prop("disabled", false);
                $("input[name='password']").prop("disabled", false);
                $("input[name='address']").prop("disabled", false);
                $("input[name='email']").prop("disabled", false);
                $("input[name='head_portrait_url']").prop("disabled", false);
                $("input[name='blog_number']").parent().parent().prop("hidden", true);
                $("input[name='comment_number']").parent().parent().prop("hidden", true);
                $("#add_edit_layer").prop("hidden",false);
            },
            end: function () {
                $("#add_edit_layer").prop("hidden",true).attr("style","");
            }
        })
        // 3.1提交按钮
        form.on('submit(form_submit)', function (data) {
            //console.log(data.elem) //被执行事件的元素DOM对象，一般为button对象
            //console.log(data.form) //被执行提交的form对象，一般在存在form标签时才会返回
            //console.log(data.field) //当前容器的全部表单字段，名值对形式：{name: value}
            let insert_load_index = layer.load(1);
            $.post("/user", {
                "token": localStorage.getItem("token"),
                "phone": $.trim(data.field.phone),
                "username": $.trim(data.field.username),
                "password": $.trim(data.field.password),
                "role_id": $.trim(data.field.role_id),
                "address": $.trim(data.field.address),
                "sex": $.trim(data.field.sex),
                "email": $.trim(data.field.email),
                "head_portrait_url": $.trim(data.field.head_portrait_url),
            }, function (result) {
                if (result.code === 200) {
                    let html_str = "";
                    html_str += '<tr><td><input type="checkbox" name="user_id" value="' + result.data.id + '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img class="layui-nav-img" src="' + result.data.headPortraitUrl + '" alt=""></td>';
                    html_str += '<td>' + result.data.phone + '</td>';
                    html_str += '<td>' + result.data.username + '</td>';
                    html_str += '<td>' + result.data.roleName + '</td>';
                    html_str += '<td>' + result.data.address + '</td>';
                    html_str += '<td>' + result.data.sex + '</td>';
                    html_str += '<td>' + result.data.email + '</td>';
                    html_str += '<td>' + result.data.blogNumber + '</td>';
                    html_str += '<td>' + result.data.commentNumber + '</td></tr>';
                    $("#user_list").prepend(html_str);
                    layer.close(add_layer_index);
                } else
                    layer.msg(result.msg, {icon: 5});
                layer.close(insert_load_index);
            })
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });
    })

    // 4.修改按钮
    $("#edit_btn").click(function () {
        let $user_checked = $("input[type='checkbox'][name='user_id']:checked");
        if ($user_checked.length !== 1) {
            layer.msg("请选择一个用户进行修改", {icon: 5});
            return false;
        }
        // 修改前先初始化
        edit_init($user_checked.val());
        let edit_layer_index = layer.open({
            type: 1,
            title: "修改",
            content: $("#add_edit_layer"),
            closeBtn: 2,
            //anim: 3,
            success: function (layero, index) {
                $("#reset_btn").addClass("layui-btn-disabled").prop("disabled", true);
                $("#add_edit_layer").prop("hidden",false);
            },
            end: function () {
                $("#add_edit_layer").prop("hidden",true).css("display","none");
            }
        })
        // 4.1提交按钮
        form.on('submit(form_submit)', function (data) {
            //console.log(data.elem) //被执行事件的元素DOM对象，一般为button对象
            //console.log(data.form) //被执行提交的form对象，一般在存在form标签时才会返回
            //console.log(data.field) //当前容器的全部表单字段，名值对形式：{name: value}
            let update_load_index = layer.load(1);
            $.ajax({
                url: "/user",
                method: "put",
                data: {
                    "token": localStorage.getItem("token"),
                    "id": $user_checked.val(),
                    //"phone": $.trim(data.field.phone),目前不让修改手机号
                    "username": $.trim(data.field.username),
                    "password": $.trim(data.field.password),
                    "role_id": $.trim(data.field.role_id),
                    "address": $.trim(data.field.address),
                    "sex": $.trim(data.field.sex),
                    //"email": $.trim(data.field.email),
                    "head_portrait_url": $.trim(data.field.head_portrait_url),
                },
                dataType: "json",
                success: function (result) {
                    if (result.code === 200) {
                        let html_str = "";
                        html_str += '<tr><td><input type="checkbox" name="user_id" value="' + result.data.id + '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img class="layui-nav-img" src="' + result.data.headPortraitUrl + '" alt=""></td>';
                        html_str += '<td>' + result.data.phone + '</td>';
                        html_str += '<td>' + result.data.username + '</td>';
                        html_str += '<td>' + result.data.roleName + '</td>';
                        html_str += '<td>' + result.data.address + '</td>';
                        html_str += '<td>' + result.data.sex + '</td>';
                        html_str += '<td>' + result.data.email + '</td>';
                        html_str += '<td>' + result.data.blogNumber + '</td>';
                        html_str += '<td>' + result.data.commentNumber + '</td></tr>';
                        $("input[type='checkbox'][name='user_id'][value='" + result.data.id + "']").parent().parent().after(html_str).remove();
                        layer.close(edit_layer_index);
                    } else
                        layer.msg(result.msg, {icon: 5});
                    layer.close(update_load_index);
                }
            })
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        })
    })

    // 5.删除按钮
    $("#delete_btn").click(function () {
        let $user_checked = $("input[type='checkbox'][name='user_id']:checked");
        if ($user_checked.length === 0) {
            layer.msg("请选择需要删除的用户", {icon: 5});
            return false;
        }
        let ids =[];
        $.each($user_checked, function (i, n) {
            ids[i]=n.value;
        })
        layer.confirm("确认删除所选中的" + $user_checked.length + "个用户吗?用户id：" + ids, {icon: 3}, function (index) {
            let delete_load_index = layer.load(1);
            $.ajax({
                url: "/user",
                method: "delete",
                data: {
                    "token": localStorage.getItem("token"),
                    "ids": ids
                },
                dataType: "json",
                traditional: true,//true开启数组参数传递
                success: function (result) {
                    if(result.code===200){
                        layer.msg(result.msg);
                        $user_checked.parent().parent().addClass("layui-bg-red");
                    }else
                        layer.msg(result.msg,{icon:5});
                    layer.close(delete_load_index);
                    layer.close(index);
                }

            })
        })

    })


    // 开始初始化
    init();
})

/*分页查询函数*/
function pageList(page_no, page_size, isRender) {
    let layer = layui.layer, laypage = layui.laypage;

    let page_load_index = layer.load(1);
    let search_phone = $("input[name='hidden_phone']").val();
    let search_username = $("input[name='hidden_username']").val();
    let search_blog_number_min = $("input[name='hidden_blog_number_min']").val();
    let search_blog_number_max = $("input[name='hidden_blog_number_max']").val();
    $("input[name='search_phone']").val(search_phone);
    $("input[name='search_username']").val(search_username);
    $("input[name='search_blog_number_min']").val(search_blog_number_min);
    $("input[name='search_blog_number_max']").val(search_blog_number_max);

    $.get("/user/info", {
        "token": localStorage.getItem("token"),
        "phone": search_phone,
        "username": search_username,
        "blog_number_min": search_blog_number_min,
        "blog_number_max": search_blog_number_max,
        "page_no": page_no,
        "page_size": page_size
    }, function (result) {
        if (result.code === 200) {
            let html_str = "";
            $.each(result.data, function (i, n) {
                html_str += '<tr><td><input type="checkbox" name="user_id" value="' + n.id + '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img class="layui-nav-img" src="' + n.headPortraitUrl + '" alt=""></td>';
                html_str += '<td>' + n.phone + '</td>';
                html_str += '<td>' + n.username + '</td>';
                html_str += '<td>' + n.roleName + '</td>';
                html_str += '<td>' + n.address + '</td>';
                html_str += '<td>' + n.sex + '</td>';
                html_str += '<td>' + n.email + '</td>';
                html_str += '<td>' + n.blogNumber + '</td>';
                html_str += '<td>' + n.commentNumber + '</td></tr>';
            })
            $("#user_list").html(html_str);
            if (isRender === true || isRender === "true") {// 需要渲染分页
                //执行一个laypage实例
                laypage.render({
                    elem: 'user_page', //注意，这里的 test1 是 ID，不用加 # 号
                    count: result.total, //数据总数，从服务端得到
                    limit: page_size,    //每页显示的条数。laypage将会借助 count 和 limit 计算出分页数。
                    theme: '#123456',//自定义主题
                    jump: function (obj, first) {//
                        // 当分页被切换时触发，函数返回两个参数：
                        // obj（当前分页的所有选项值）、first（是否首次，一般用于初始加载的判断）
                        //obj包含了当前分页的所有参数，比如：
                        //console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
                        //console.log(obj.limit); //得到每页显示的条数

                        //首次不执行
                        if (!first) {
                            //do something
                            pageList(obj.curr, obj.limit, false);//不渲染
                        }
                    }
                });
            }
        } else if (result.code === 401)
            window.location.href = "/login.html";
        else
            layer.msg(result.msg, {icon: 5});
        layer.closeAll("loading");
    })
}

/*修改前初始化函数*/
function edit_init(id) {
    let layer = layui.layer;
    let edit_load_index = layer.load(1);
    $.get("/user/infoWithPwd", {"token": localStorage.getItem("token"), "id": id}, function (result) {
        if (result.code === 200) {
            $("input[name='phone']").val(result.data.phone).prop("disabled", true);
            $("input[name='username']").val(result.data.username).prop("disabled", false);
            $("input[name='password']").val(result.data.password).prop("disabled", false);
            check_role_sex(result.data.roleName, result.data.sex);//给角色和性别选中
            $("input[name='address']").val(result.data.address).prop("disabled", false);
            $("input[name='email']").val(result.data.email).prop("disabled", true);
            $("input[name='head_portrait_url']").val(result.data.headPortraitUrl).prop("disabled", false);
            $("input[name='blog_number']").val(result.data.blogNumber).prop("disabled", true)
                .parent().parent().prop("hidden", false);
            $("input[name='comment_number']").val(result.data.commentNumber).prop("disabled", true)
                .parent().parent().prop("hidden", false);
        } else
            layer.msg(result.msg, {icon: 5});
        layer.close(edit_load_index);
    })
}

/*选中角色和性别的函数*/
function check_role_sex(role_name, sex) {
    $("input[name='role_id'][title='" + role_name + "']").attr("checked", true);
    $("input[name='sex'][value='" + sex + "']").attr("checked", true);
    // 更新渲染
    layui.form.render("radio");
}
